import React from 'react';
import { Card, Input, Modal, Row, Col, List, Tooltip, Upload, InputNumber, message } from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import { pageSize, modalWidth, apiUrl, uploadImageSizeUpper } from '../../../config';
import { PageHeaderLayout, IconButton, PageCard } from '../../components';
import tools from '../../utils';
import Authorized from '../../utils/Authorized';
import styles from './image.css';

const reqApi = 'image';
const formItemLayout = {
  labelCol: { md: 3 },
  wrapperCol: { md: 21 },
};
const formItemLayout2 = {
  labelCol: { md: 6, xs: 7 },
  wrapperCol: { md: 18, xs: 17 },
};
const imageLimitSize = 720; // 图片限定尺寸(宽和高都不能超过这个值)

class page extends React.Component {
  state = {
    loading: false,
    visible: false,
    dialogTitle: '',
    dialogAction: 'create',
    dialogLoading: false,
    editId: 0,
    cardHeight: 0, // 卡片高度
  };

  componentDidMount() {
    this.funcGetListData();
    window.onresize = this.funcHeight;
  }

  componentWillUnmount() {
    window.onresize = null;
  }

  // 设置卡片高度
  funcHeight = () => {
    const cardBody = document.getElementsByClassName('cardBody');
    if (cardBody.length) {
      const cardHeight = Math.round(cardBody[0].clientWidth / 1.5);
      this.setState({ cardHeight });
    }
  }

  // 获取列表数据
  funcGetListData = () => {
    this.setState({ loading: true });

    const { dispatch } = this.props;

    dispatch({
      type: reqApi + '/list',
      payload: {
        currentPage: 1,
        pageSize: 100,
      },
    }).then(() => this.setState({ loading: false }, this.funcHeight));
  };

  // 弹出表单
  funcOpenForm = (record) => {
    const dialogAction = record ? "edit" : "create";

    this.setState({
      visible: true,
      dialogTitle: tools.funcDlgTitle("轮播图", dialogAction),
      dialogAction,
      uploading: false,
    }, () => {
      const { form } = this.props;

      form.resetFields();

      if (dialogAction === "edit") {
        const { title, src, sequ } = record;
        const newRecord = {
          title,
          src,
          sequ,
        };
        form.setFieldsValue(newRecord);
      }
    });
  };

  // 保存
  funcSave = () => {
    const { dialogAction, editId, editorText } = this.state;
    const { form, dispatch } = this.props;

    form.validateFields((error, values) => {
      if (error) return error;

      const model = {
        ...values,
        content: editorText,
      };
      if (dialogAction === "edit") model.id = editId;
      if (!values.userId || values.userId === '0')
        model.userId = tools.funcGetUserId();

      this.setState({ dialogLoading: true });

      dispatch({
        type: reqApi + '/' + dialogAction,
        payload: { model },
      }).then(() => {
        this.setState({ dialogLoading: false });

        const { props } = this;
        const { success } = props[reqApi];
        if (success) {
          this.setState({ visible: false });
          this.funcGetListData();
        }
      });
    });
  };

  // 删除
  funcDelete = (record) => {
    Modal.confirm({
      title: '删除?',
      content: (
        <div>
          <div>你即将删除以下记录:</div>
          <div>{record.title}</div>
          <div>请确认是否删除?</div>
        </div>
      ),
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk: () => {
        this.setState({ loading: true });

        const { dispatch } = this.props;
        dispatch({
          type: reqApi + "/dele",
          payload: { ids: record.id },
        }).then(() => {
          const { props } = this;
          const { success } = props[reqApi];
          if (success) this.funcGetListData();
        });
      },
    });
  };

  // 检查图片是否有效
  funcCheckFile = (file) => {
    const size = 1024 * 1024 * uploadImageSizeUpper;

    let isOk = true;
    if (file.size > size) {
      message.error(file.name + " 不能超过 " + uploadImageSizeUpper + "MB");
      isOk = false;
    }

    if (isOk) {
      const reader = new FileReader();
      reader.onload = (e) => this.funcDisposeFile(e, file, this.funcUploadFile);
      reader.readAsDataURL(file);
    } else this.setState({ uploading: false });
    return false;
  };

  // 处理源图
  funcDisposeFile = (e, file, callback) => {
    const fileExt = file.name.substr(file.name.lastIndexOf(".") + 1);
    let b64 = e.target.result;
    const img = new Image();
    img.onload = () => {
      // 例外处理, 低分辨率的源图则没必要进行处理
      if (img.width <= imageLimitSize) {
        callback(b64.split(",")[1], fileExt);
        return;
      }

      // 轮播图宽度固定是"imageLimitSize"的值
      const ratio = img.width / img.height;
      img.width = imageLimitSize;
      img.height = Math.round(imageLimitSize / ratio);

      const canvas = document.createElement("canvas");
      const ct = canvas.getContext("2d");
      canvas.width = img.width;
      canvas.height = img.height;
      ct.drawImage(img, 0, 0, img.width, img.height);
      b64 = canvas.toDataURL(file.type, 0.9);

      callback(b64.split(",")[1], fileExt);
    };
    img.src = b64;
  };

  // 开始上传图片
  funcUploadFile = (b64, imgType) => {
    const payload = {
      b64,
      imgType,
    };
    const { dispatch } = this.props;
    dispatch({
      type: reqApi + '/upload',
      payload,
    }).then(() => {
      this.setState({ uploading: false });
      const { props } = this;
      const { success, uploadUrl } = props[reqApi];
      if (success) props.form.setFieldsValue({ src: uploadUrl });
    });
  };

  // 包装路径为可访问的网络地址
  pathWrap = path => apiUrl() + '/upload/' + path;

  render() {
    const { state, props } = this;
    const { data, total } = props[reqApi];
    const { getFieldDecorator } = props.form;
    let gridGutter = 16;
    if (window.isPad) gridGutter = 8;
    if (window.isMobile) gridGutter = 0; // gutter>0在手机屏上会导致另起一行

    return (
      <PageHeaderLayout title={props.route.name}>
        <PageCard
          children={(
            <div>
              <Authorized authority={() => tools.funcCheckValid(props, 'create')}>
                <IconButton
                  text='新增轮播图'
                  onClick={() => this.funcOpenForm()}
                  style={{ marginRight: 16 }}
                />
              </Authorized>

              <span>{total ? '共 ' + total + ' 张轮播图' : '暂无轮播图, 请新增'}</span>
              <br />
              <br />

              <List
                dataSource={data}
                loading={state.loading}
                grid={{ xxl: 4, xl: 4, lg: 4, md: 3, sm: 2, xs: 1, gutter: gridGutter }}
                renderItem={(item) => (
                  <List.Item key={item.id}>
                    <Card
                      size='small'
                      title={item.title}
                      bodyStyle={{ padding: '1px 0 0 0' }}
                      actions={[
                        <div key='edit' className={styles.iconView}>
                          <Tooltip title='编辑'>
                            <Icon
                              type='edit'
                              className={styles.iconEdit}
                              onClick={() => {
                                this.setState({ editId: item.id });
                                this.funcOpenForm(item);
                              }}
                            />
                          </Tooltip>
                        </div>,
                        <div key='delete' className={styles.iconView}>
                          <Tooltip title='删除'>
                            <Icon
                              type='delete'
                              className={styles.iconDelete}
                              onClick={() => this.funcDelete(item)}
                            />
                          </Tooltip>
                        </div>,
                      ]}
                    >
                      <div className='cardBody'>
                        <div
                          className={styles.imageView}
                          style={{
                            backgroundImage: 'url("' + this.pathWrap(item.src) + '")',
                            height: state.cardHeight,
                          }}
                        />
                      </div>
                    </Card>
                  </List.Item>
                )}
              />
            </div>
          )}
        />

        <Modal
          width={modalWidth}
          title={state.dialogTitle}
          visible={state.visible}
          bodyStyle={{
            padding: window.isMobile ? '24px 24px 0 24px' : '24px 24px 0 0',
          }}
          onOk={this.funcSave}
          onCancel={() => this.setState({ visible: false })}
          footer={[
            <IconButton
              key='cancel'
              text='取消'
              type='default'
              onClick={() => this.setState({ visible: false })}
            />,
            <IconButton
              key='save'
              text='保存'
              onClick={this.funcSave}
              loading={state.dialogLoading}
            />,
          ]}
        >
          <Form>
            <Row gutter={{ md: 24, sm: 8 }}>
              <Col md={24} sm={24}>
                <Form.Item label="标题" {...formItemLayout}>
                  {getFieldDecorator("title", {
                    rules: [{ required: true, message: "请输入轮播图标题" }],
                  })(<Input maxLength={255} autoFocus />)}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="图片" {...formItemLayout2}>
                  {getFieldDecorator("src", {
                    rules: [{ required: true, message: "请选择一张轮播图图片并上传" }],
                  })(
                    <Input
                      disabled={state.uploading}
                      suffix={
                        state.uploading ? <Icon type="loading" /> : (
                          <Upload
                            accept="image/*"
                            showUploadList={false}
                            beforeUpload={(file) => {
                              if (state.uploading) return false;
                              this.setState({ uploading: true }, () => this.funcCheckFile(file));
                            }}
                          >
                            <Tooltip title="选择图片">
                              <Icon type="upload" />
                            </Tooltip>
                          </Upload>
                        )
                      }
                    />
                  )}
                </Form.Item>
              </Col>

              <Col md={12} sm={24}>
                <Form.Item label="显示顺序" {...formItemLayout2}>
                  {getFieldDecorator("sequ", {
                    initialValue: 0,
                  })(<InputNumber min={0} max={1000} style={{ width: '100%' }} />)}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </PageHeaderLayout>
    );
  }
}

const page2 = Form.create()(page);
export default connect(({ image, menu }) => ({ image, menu }))(page2);
